'use strict';
//define(['common','angular','services'], function(common,angular) {
	angular.module('backcenter.permissionList', [])

	.controller('permissionListCtrl',['$rootScope', '$scope', '$stateParams', '$state'
		, '$uibModal', 'BizData', '$ocLazyLoad'
	                             , f])
    function f($rootScope,$scope,$stateParams,$state
    		, $uibModal, BizData, $ocLazyLoad
	                            		 ) {

		var Model = this;
		
		console.log('$stateParams-->>',$stateParams);



		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataPermissionBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataPermissionAfterDelete = function(event) {
//			alert('删除之后！')
		}



		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataPermissionIndexChanged = function(event) {
			
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataPermissionDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataPermissionValueChanged = function(event) {
			
		}
		

		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataPermissionBeforeNew = function(event) {

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataPermissionAfterNew = function(event){
			
		};
		
		Model.dataPermissionAfterRefresh = function(event){
			console.log('Model.dataPermissionAfterRefresh.event-->>',event);
		};
	
		
		var options = {};
		options.container = Model;
		options.concept = 'SaOppermission';
		options.name = 'dataPermission';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '';
		options.reader = '/backcenter/permission/list/query';
		options.writer = '/backcenter/permission/list/save';
		options.deleter = '/backcenter/permission/list/delete';
		options.idColumnDefine = "sID";
		options.idColumnName = "sID";
		options.isTree = false;
		options.parentRelation = 'sParent';
		options.nodeKindRelation = 'sNodeKind';
		options.nodeLevelRelation = 'sLevel';
		options.pathRelation = 'sFID';
		options.directDeleteMode = true;
		options.limit = 10;
		options.orderBy = "sActivityFName ASC";
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataPermissionIndexChanged;
		options.onBeforeNew = Model.dataPermissionBeforeNew;
		options.onAfterNew = Model.dataPermissionAfterNew;
		options.onBeforeDelete = Model.dataPermissionBeforeDelete;
		options.onAfterDelete = Model.dataPermissionAfterDelete;
		options.onValueChanged = Model.dataPermissionValueChanged;
		options.onDataChanged = Model.dataPermissionDataChanged;
		options.onAfterRefresh = Model.dataPermissionAfterRefresh;
		
		$scope.dataPermission = new BizData(options);

		//监视对象中的所有变动
		$scope.dataPermission.deregRows = $scope.$watch('dataPermission.rows',$scope.dataPermission.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		
//		var options = {};
//		options.container = Model;
//		options.concept = 'SaOppermission';
//		options.name = 'dataPermission1';
//		options.url = $rootScope.path;
//		options.httpUrl = $rootScope.getServiceName();
//		options.creater = '';
//		options.reader = '/backcenter/permission/list/query';
//		options.writer = '/backcenter/permission/list/save';
//		options.deleter = '/backcenter/permission/list/delete';
//		options.idColumnDefine = "sID";
//		options.idColumnName = "sID";
//		options.isTree = false;
//		options.parentRelation = 'sParent';
//		options.nodeKindRelation = 'sNodeKind';
//		options.nodeLevelRelation = 'sLevel';
//		options.pathRelation = 'sFID';
//		options.directDeleteMode = true;
//		options.limit = 10;
//		options.orderBy = "sActivityFName ASC";
//		
//		options.onIndexChanging = null;
//		options.onIndexChanged = Model.dataPermissionIndexChanged;
//		options.onBeforeNew = Model.dataPermissionBeforeNew;
//		options.onAfterNew = Model.dataPermissionAfterNew;
//		options.onBeforeDelete = Model.dataPermissionBeforeDelete;
//		options.onAfterDelete = Model.dataPermissionAfterDelete;
//		options.onValueChanged = Model.dataPermissionValueChanged;
//		options.onDataChanged = Model.dataPermissionDataChanged;
		
//		$scope.dataPermission1 = new BizData(options);

		//监视对象中的所有变动
//		$scope.dataPermission1.deregRows = $scope.$watch('dataPermission1.rows',$scope.dataPermission1.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		
		////////////////////启动执行开始///////////////////////////////////////////////////

		/*
		//添加角色//跳转到角色列表页面
		Model.addRoles = function(item) {
			var id = item.sID.value;
			var to = '/backcenter/role/list';
			var params = {
					"id":id
					,"sLongName":item.sLongName.value
					,"sName":item.sName.value
					,"recordState":"none"
					};
			var options = {};
			$state.go(to,params,options);
		}
		*/
		
		//接收调用的参数
		Model.params = $stateParams; 

    	
    	if($rootScope.checkTopMyOgn()==true){
			$scope.dataPermission.filter = "SaOppermission.sPermissionRoleID='"+Model.params.roleID+"'"
			+ " AND SaOppermission.sPermissionKind=0"
			;
			$scope.dataPermission.refreshData();
//			$scope.dataPermission1.filter = "SaOppermission.sPermissionRoleID='"+Model.params.rleID+"'"
//			+ " AND SaOppermission.sPermissionKind=1"
//			;
//			$scope.dataPermission1.refreshData();
    	}


		////////////////////启动执行结束///////////////////////////////////////////////////
			

		Model.saveDataPermission = function(){
			$scope.dataPermission.saveData();
		};


		
		//打开对话框（选择权限）
		Model.triggerSelectPermissionClick = function(){
			var options = {};
			
			options.recordState = 'none';
			options.id = $rootScope.topMyOgn.sID;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/sysInfo/selectMulti',  
	            controller: 'sysInfoSelectMultiCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/sysInfo/selectMulti')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	console.log('returnData-->>',returnData);
	         	//debugger;
	             try {
	            	 
	            	//选择的权限的ids
	             	var sysInfos = new Array();
	            	 
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//只收集类型为页面pag和权限act的ID
	             		if(returnData[i].systemKind=='pag' /*|| returnData[i].systemKind=='act'*/){
	             			//console.log('returnData[i]-->>',returnData[i]);
	             			var obj = new Object();
	             			obj.systemFullID = returnData[i].systemFullID;
	             			obj.systemFullName = returnData[i].systemFullName;
	             			obj.absoluteUrl = returnData[i].absoluteUrl;
	             			sysInfos.push(obj);
	             		}
	                }
	             	console.log('sysInfos-->>',sysInfos);
	             	if(sysInfos.length<=0){
	             		return 0;
	             	}
	             	
	             	//当前组织的ids
             		var roleIDs = new Array();
             		roleIDs[0] = Model.params.roleID; 
             		
             		var data = {};
            		data.roleIDs = roleIDs;
             		data.sysInfos = sysInfos;
	             	
	    			//提交保存
             		
					var response = $.ajax({
			            type: "POST",
			            async : false,
			            url: $rootScope.getProjectName() + "/backcenter/permission/list/add",
			            data: JSON.stringify(data),// "{}",
			            contentType: "application/json; charset=utf-8",
			            dataType: "json",
//			            processData: false,
			            success: function (data) {
			                // Play with returned data in JSON format
			            },
			            error: function (msg) {
//			                alert(msg.responseText);
			            }
			        });
	            	console.log('Model.triggerSelectPermissionClick.response-->>',response);

					if (response.readyState == 4 && response.status == 200) {
	    				$scope.dataPermission.refreshPageData();
	    				return 0;
	    			}else{
	    				alert('保存失败！')
	    				return -1;
	    			}
	    			

	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		//（删除权限）
		Model.triggerDeletePermissionClick = function(){
			var ids = new Array();
			for(var index=0;index<$scope.dataPermission.rows.length;index++){
				if($scope.dataPermission.rows[index].userdata.checked){
					ids.push($scope.dataPermission.rows[index].sID.value);
				}
			}
			$scope.dataPermission.deleteData(ids);
			$scope.dataPermission.refreshData();
		};

		//打开对话框（选择actions）
		Model.triggerSelectActionClick = function(sID,systemFullID,sActions){

			var options = {};
			options.recordState = 'none';
			options.id = systemFullID;
			options.sActions = sActions;

	        //var modalInstance = systemService.openActionDialog(options);
	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/sysAction/selectMulti',  
	            controller: 'actionSelectMultiCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/sysAction/selectMulti.js')
		        }
	        });  

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	            	 
	            	//开始装配actions
	            	
	             	var actionsArray = new Array();
	            	 
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//
	            		//[{name:"create",label:"新增"},{name:"delete",label:"删除"},{name:"save",label:"修改"},{name:"query",label:"查询"}];
//	             		var action = {}
//	             		action.name = returnData[i].absoluteUrl;
//	             		action.label = returnData[i].systemName;
	             		actionsArray.push(returnData[i].actionCode);
	             		
	                }
	             	
	             	var actions = null;
	             	
	             	if(actionsArray.length>0){
	             		actions = actionsArray.join(",");
	             	}
             		
             		var data = new Object();
            		data.id = sID;
             		data.actions = actions;
 	             	
//             		data = JSON.stringify(data);
//             		data = JSON.parse(data);
//             		alert(data);
             		
	    			//提交保存
             		
             		/*
					var response = $.ajax({
			            type: "POST",
			            async : false,
			            url: $rootScope.getProjectName() + "/backcenter/permission/add",
			            data: JSON.stringify(data),// "{}",
			            contentType: "application/json; charset=utf-8",
			            dataType: "json",
//			            processData: false,
			            success: function (data) {
			                // Play with returned data in JSON format
			            },
			            error: function (msg) {
//			                alert(msg.responseText);
			            }
			        });
					*/
					var response = $.ajax({
			            type: "POST",
			            async : false,
			            url: $rootScope.getProjectName() + "/backcenter/permission/list/updateActionsByID",
			            data: JSON.stringify(data), //data,// "{}",
			            contentType: "application/json; charset=utf-8",
			            dataType: "json",
//			            processData: false,
			            success: function (data) {
			                // Play with returned data in JSON format
			            },
			            error: function (msg) {
//			                alert(msg.responseText);
			            }
			        });

					if (response.readyState == 4 && response.status == 200) {
	    				$scope.dataPermission.refreshPageData();
	    				return 0;
	    			}else{
	    				alert('保存失败！')
	    				return -1;
	    			}
	    			

	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};

		
		//打开对话框（选择数据权限）
		Model.triggerSelectPermission1Click = function(){
			var options = {};
			
			options.recordState = 'none';
			options.id = $rootScope.topMyOgn.sID;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/org/selectMulti',  
	            controller: 'orgSelectMultiCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/org/selectMulti')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	            	 
	            	//选择的权限的ids
	             	var orgIDs = new Array();
	            	 
	             	for ( var i = 0; i < returnData.length; i++) {
	             		orgIDs.push(returnData[i].sID);
	                 }
	             	if(orgIDs.length<=0){
	             		return 0;
	             	}
	             	
	             	//当前组织的ids
//             		var dataMaster = $scope.dataRole;
//             		var rowID = dataMaster.getCurrentID();
             		var roleIDs = new Array();
             		roleIDs[0] = rowID; 
             		
             		var data = {};
            		data.roleIDs = roleIDs;
             		data.orgIDs = orgIDs;
	             	
	    			//提交保存
             		
					var response = $.ajax({
			            type: "POST",
			            async : false,
			            url: $rootScope.getProjectName() + "/backcenter/permission/list/add1",
			            data: JSON.stringify(data),// "{}",
			            contentType: "application/json; charset=utf-8",
			            dataType: "json",
//			            processData: false,
			            success: function (data) {
			                // Play with returned data in JSON format
			            },
			            error: function (msg) {
//			                alert(msg.responseText);
			            }
			        });

					if (response.readyState == 4 && response.status == 200) {
	    				$scope.dataPermission1.refreshPageData();
	    				return 0;
	    			}else{
	    				alert('保存失败！')
	    				return -1;
	    			}
	    			

	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		}
		//（删除权限）
		Model.triggerDeletePermission1Click = function(){
			var ids = new Array();
			for(var index=0;index<$scope.dataPermission1.rows.length;index++){
				if($scope.dataPermission1.rows[index].userdata.checked){
					ids.push($scope.dataPermission1.rows[index].sID.value);
				}
			}
			$scope.dataPermission1.deleteData(ids);
			$scope.dataPermission1.refreshData();
		}
		

	    //表格标题中的选择框ng-model
	    $scope.checkboxPermissionValue = false;
	    //表格标题中的选择对话框click事件
	    Model.checkboxPermissionClick = function () {  
	    	$scope.checkboxPermissionValue=!$scope.checkboxPermissionValue;
//	    	console.log('$scope.checkboxPermissionValue-->',$scope.checkboxPermissionValue);
			for(var index=0;index<$scope.dataPermission.rows.length;index++){
				$scope.dataPermission.rows[index].userdata.checked=$scope.checkboxPermissionValue;
			}
	    };    
	    //表格标题中的选择框ng-model
	    $scope.checkboxPermissionValue1 = false;
	    //表格标题中的选择对话框click事件
	    Model.checkboxPermissionClick1 = function () {  
	    	$scope.checkboxPermissionValue1=!$scope.checkboxPermissionValue1;
//	    	console.log('$scope.checkboxPermissionValue1-->',$scope.checkboxPermissionValue1);
			for(var index=0;index<$scope.dataPermission1.rows.length;index++){
				$scope.dataPermission1.rows[index].userdata.checked=$scope.checkboxPermissionValue1;
			}
	    };    

	    ///////////////////////////页面级////////////////////////////////////////
		//返回
		Model.goBack = function(event) {
			window.history.go(-1);
		}
	    ///////////////////////////页面级////////////////////////////////////////

		return Model;
		
	}	
	
//});
